package com.example.wzdjcrdpassword.service;

import com.example.wzdjcrdpassword.entity.UserReport;
import com.example.wzdjcrdpassword.repository.UserReportRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserReportService {
    
    private final UserReportRepository userReportRepository;
    
    /**
     * 创建用户数据上报记录
     */
    public UserReport createUserReport(String macAddress, String accountInfo, String heroInfo, String otherInfo) {
        UserReport userReport = new UserReport();
        userReport.setBusinessId(generateBusinessId());
        userReport.setMacAddress(macAddress);
        userReport.setAccountInfo(accountInfo);
        userReport.setHeroInfo(heroInfo);
        userReport.setOtherInfo(otherInfo);
        
        UserReport savedReport = userReportRepository.save(userReport);
        log.info("用户数据上报记录创建成功，MAC地址: {}, 业务ID: {}", macAddress, savedReport.getBusinessId());
        return savedReport;
    }
    
    /**
     * 根据业务ID查询数据上报记录
     */
    public UserReport getUserReportByBusinessId(String businessId) {
        return userReportRepository.findByBusinessId(businessId);
    }
    
    /**
     * 根据MAC地址查询数据上报记录
     */
    public List<UserReport> getUserReportsByMacAddress(String macAddress) {
        return userReportRepository.findByMacAddressAndIsDeleted(macAddress, "NO");
    }
    
    /**
     * 查询所有有效的数据上报记录
     */
    public List<UserReport> getAllActiveReports() {
        return userReportRepository.findAllActiveReports();
    }
    
    /**
     * 根据MAC地址和时间范围查询数据上报记录
     */
    public List<UserReport> getUserReportsByMacAddressAndTimeRange(String macAddress, LocalDateTime startTime, LocalDateTime endTime) {
        return userReportRepository.findByMacAddressAndTimeRange(macAddress, startTime, endTime);
    }
    
    /**
     * 逻辑删除数据上报记录
     */
    public boolean deleteUserReport(String businessId) {
        UserReport userReport = userReportRepository.findByBusinessId(businessId);
        if (userReport != null && "NO".equals(userReport.getIsDeleted())) {
            userReport.setIsDeleted("YES");
            userReportRepository.save(userReport);
            log.info("用户数据上报记录已逻辑删除，业务ID: {}", businessId);
            return true;
        }
        return false;
    }
    
    /**
     * 生成32位业务ID
     */
    private String generateBusinessId() {
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }
    
    /**
     * 验证JSON数据格式
     */
    public boolean validateJsonData(String jsonData) {
        if (jsonData == null || jsonData.trim().isEmpty()) {
            return true; // 允许空值
        }
        
        try {
            // 简单的JSON格式验证
            return jsonData.trim().startsWith("{") && jsonData.trim().endsWith("}");
        } catch (Exception e) {
            log.warn("JSON数据格式验证失败: {}", jsonData);
            return false;
        }
    }
    
    /**
     * 验证MAC地址格式
     */
    public boolean validateMacAddress(String macAddress) {
        if (macAddress == null || macAddress.trim().isEmpty()) {
            return false;
        }
        
        // 简单的MAC地址格式验证（支持多种格式）
        String macRegex = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9A-Fa-f]{12})$";
        return macAddress.trim().matches(macRegex);
    }
}